from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import User
from django_redis import get_redis_connection
import random
from . import constants
from celery_tasks.sms.tasks import send_sms_code


class SmscodeView(APIView):
    def get(self, request, mobile):
        # 接收手机号，已经从路径中获取
        # 检查：此手机号是否已经使用
        # if User.objects.filter(mobile=mobile).count() > 0:
        #     return Response({'message': "手机号已经存在"})

        # 连接redis
        redis_cli = get_redis_connection('smscode')

        # 检查：是否已经向此手机号发短信
        if redis_cli.get('sms_flag_' + mobile):
            return Response({'message': "请稍候再向此手机号发短信"})

        # 生成随机6位数
        code = random.randint(100000, 999999)

        # 存储验证码、发送标记
        # redis_cli.setex('sms_' + mobile, constants.SMS_CODE_EXPIRES, code)
        # redis_cli.setex('sms_flag_' + mobile, constants.SMS_FLAG_EXPIRES, 1)
        # 优化：此处会多次连接并断开与Redis服务器的交互，使用管道一次执行多条命令
        redis_pipeline = redis_cli.pipeline()
        redis_pipeline.setex('sms_' + mobile, constants.SMS_CODE_EXPIRES, code)
        redis_pipeline.setex('sms_flag_' + mobile, constants.SMS_FLAG_EXPIRES, 1)
        redis_pipeline.execute()

        # 调用第三方sdk发短信
        # print(code)
        # 调用异步任务：通知代理人
        send_sms_code.delay(mobile, code)

        return Response({'message': "OK，发送成功"})
